/**
 * Copyright (c) 2023, iDearHanYu Co., Ltd.
 *
 * SPDX-License-Identifier: 
 *
 * Change Logs:
 * Date           Author       Notes
 * 2024-08-16     chao         first version
 */

#include <lvgl.h>
#include <stdio.h>
#include <stdlib.h>
#include "lcd.h"

/*A static or global variable to store the buffers*/
static lv_disp_draw_buf_t disp_buf;

/*Descriptor of a display driver*/
static lv_disp_drv_t disp_drv;

/*Static or global buffer(s). The second buffer is optional*/
//static lv_color_t buf_1[MY_DISP_HOR_RES * DISP_BUFFER_LINES];
static lv_color_t *buf_1;

/*Flush the content of the internal buffer the specific area on the display
 *You can use DMA or any hardware acceleration to do this operation in the background but
 *'lv_disp_flush_ready()' has to be called when finished.*/
static void disp_flush(lv_disp_drv_t * disp_drv, const lv_area_t * area, lv_color_t * color_p)
{
    /* color_p is a buffer pointer; the buffer is provided by LVGL */
//    lcd_fill(area->x1, area->y1, area->x2, area->y2, (uint16_t *)color_p);
    uint16_t x, y;
    lcd_color_t *color = (lcd_color_t *)color_p;

    for (y=area->y1; y<=area->y2; y++)
    {
        for (x=area->x1; x<=area->x2; x++)
        {
            lcd_write_pixel(x, y, *color);
            color++;
        }
    }

    /*IMPORTANT!!!
     *Inform the graphics library that you are ready with the flushing*/
    lv_disp_flush_ready(disp_drv);
}

void lv_port_disp_init(void)
{
    buf_1 = (lv_color_t *)malloc(lcd_get_x_size()*lcd_get_y_size()*sizeof(lv_color_t));
    if (buf_1 == NULL)
    {
        LV_LOG_USER("lvgl buf_1 malloc fail\n");
    }
    else
    {
        LV_LOG_USER("lvgl buf_1 malloc success\n");
    }
    /*Initialize `disp_buf` with the buffer(s). With only one buffer use NULL instead buf_2 */
    lv_disp_draw_buf_init(&disp_buf, buf_1, NULL, lcd_get_x_size() * lcd_get_y_size());

    lv_disp_drv_init(&disp_drv); /*Basic initialization*/

    /*Set the resolution of the display*/
    disp_drv.hor_res = lcd_get_x_size();
    disp_drv.ver_res = lcd_get_y_size();

    /*Set a display buffer*/
    disp_drv.draw_buf = &disp_buf;

    /*Used to copy the buffer's content to the display*/
    disp_drv.flush_cb = disp_flush;

    /*Finally register the driver*/
    lv_disp_drv_register(&disp_drv);
}


